<?php

namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\DistributionOrder
 *
 * @property int $id
 * @property int $order_id 订单id
 * @property string $order_num 订单号
 * @property float $amount 价格
 * @property int $buyer_user_id 下单用户
 * @property int $signed_user_id 签约分销商
 * @property int $first_user_id 一级返佣接收人
 * @property int $second_user_id 二级返佣接收人
 * @property int $third_user_id 三级返佣接收人
 * @property int $success 0未完成，1已完成，2已取消
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereBuyerUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereFirstUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereOrderId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereOrderNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereSecondUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereSignedUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereSuccess($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereThirdUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Query\Builder|\App\DistributionOrder onlyTrashed()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\DistributionOrder whereDeletedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\DistributionOrder withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\DistributionOrder withoutTrashed()
 */
class DistributionOrder extends Model
{
    use SoftDeletes;
    public static function addDistributionOrder($order_id = 0,$order_num = '',$amount = 0,$buyer_user_id = 0 ){
        if ($order_id == 0)
            return 0;
        $team_info = new TeamsInfo($buyer_user_id);
        if (!$team_info->first_user_id)
            return 0;
        DB::beginTransaction();
        $record = new DistributionOrder();
        $record->order_id    = $order_id;
        $record->order_num   = $order_num;
        $record->amount      = $amount;
        $record->buyer_user_id = $buyer_user_id;
        $record->signed_user_id  = $team_info->special_appointment;
        $record->first_user_id   = $team_info->first_user_id;
        $record->second_user_id  = $team_info->second_user_id;
        $record->third_user_id   = $team_info->third_user_id;
        $record->save();
        //TODO ADD CommissionDetails() if necessary;
        DB::commit();

    }
    public static function setDistributionOrderSuccess($order_id): int
    {
        \Log::error("doing_order_success=================================");
        DB::beginTransaction();
        /** @var DistributionOrder $record */
        $record = DistributionOrder::whereOrderId($order_id)->lockForUpdate()->first();
        if (!$record) {
            DB::rollBack();
            return 0;
        }
        if ($record->success > 0) {
            DB::rollBack();
            return 0;
        }

        $record->success = 1;
        $record->save();
        \Log::error("order_success=================================");
        if ($record->amount > 0){
            $highest_level = DistributionConfig::getHighestLevel();

            if ($highest_level >= 1){
                if ($record->first_user_id != 0) {
                    //未检查first_user_id的user是否存在
                    $rule = DistributionList::getMyRule($record->first_user_id);
                    if ($rule){
                        $firstMoney = round($record->amount * $rule->first_ratio ,2);
                        $first = Commission::whereUserId($record->first_user_id)->lockForUpdate()->first();
                        if (!$first) {
                            $first = new Commission();
                            $first->user_id = $record->first_user_id;
                            $first->available_money = 0;
                        }
                        //加钱
                        $first->available_money = round($first->available_money + $firstMoney,2);
                        $first->save();
                        //加记录
                        $first_record               = new CommissionDetail();
                        $first_record->user_id      = $record->first_user_id;
                        $first_record->from_user_id = $record->buyer_user_id;
                        $first_record->order_num    = $record->order_num;
                        $first_record->order_created_at         = $record->created_at;
                        $first_record->pay_amount               = $record->amount;
                        $first_record->distribution_nickname    = UserInfo::getNickName($first_record->user_id);
                        $first_record->distribution_level       = $rule->rule_name;
                        $first_record->level                    = 1;
                        $first_record->type                     = 1;
                        $first_record->amount                   = $firstMoney;
                        $first_record->rate                     = $rule->first_ratio;
                        $first_record->status                   = 1;
                        $first_record->arrival_time             = date('Y-m-d H:i:s');
                        $first_record->save();

                    }
                }
            }

            if ($highest_level >= 2){
                if ($record->second_user_id != 0) {
                    //未检查second_user_id的user是否存在
                    $rule = DistributionList::getMyRule($record->second_user_id);
                    if ($rule){
                        $secondMoney = round($record->amount * $rule->secondary_ratio ,2);
                        $second = Commission::whereUserId($record->second_user_id)->lockForUpdate()->first();
                        if (!$second) {
                            $second = new Commission();
                            $second->user_id = $record->second_user_id;
                            $second->available_money = 0;
                        }
                        //加钱
                        $second->available_money = round($second->available_money + $secondMoney,2);
                        $second->save();
                        //加记录
                        $second_record               = new CommissionDetail();
                        $second_record->user_id      = $record->second_user_id;
                        $second_record->from_user_id = $record->buyer_user_id;
                        $second_record->order_num    = $record->order_num;
                        $second_record->order_created_at         = $record->created_at;
                        $second_record->pay_amount               = $record->amount;
                        $second_record->distribution_nickname    = UserInfo::getNickName($second_record->user_id);
                        $second_record->distribution_level       = $rule->rule_name;
                        $second_record->level                    = 2;
                        $second_record->type                     = 1;
                        $second_record->amount                   = $secondMoney;
                        $second_record->rate                     = $rule->secondary_ratio;
                        $second_record->status                   = 1;
                        $second_record->arrival_time             = date('Y-m-d H:i:s');
                        $second_record->save();

                    }
                }
            }

            if ($highest_level >= 3) {
                if ($record->third_user_id != 0) {
                    //未检查first_user_id的user是否存在
                    $rule = DistributionList::getMyRule($record->third_user_id);
                    if ($rule){
                        $threeMoney = round($record->amount * $rule->three_ratio ,2);
                        $third = Commission::whereUserId($record->third_user_id)->lockForUpdate()->first();
                        if (!$third) {
                            $third = new Commission();
                            $third->user_id = $record->third_user_id;
                            $third->available_money = 0;
                        }
                        //加钱
                        $third->available_money = round($third->available_money + $threeMoney,2);
                        $third->save();
                        //加记录
                        $third_record               = new CommissionDetail();
                        $third_record->user_id      = $record->third_user_id;
                        $third_record->from_user_id = $record->buyer_user_id;
                        $third_record->order_num    = $record->order_num;
                        $third_record->order_created_at         = $record->created_at;
                        $third_record->pay_amount               = $record->amount;
                        $third_record->distribution_nickname    = UserInfo::getNickName($third_record->user_id);
                        $third_record->distribution_level       = $rule->rule_name;
                        $third_record->level                    = 3;
                        $third_record->type                     = 1;
                        $third_record->amount                   = $threeMoney;
                        $third_record->rate                     = $rule->three_ratio;
                        $third_record->status                   = 1;
                        $third_record->arrival_time             = date('Y-m-d H:i:s');
                        $third_record->save();
                    }
                }
            }

        }

        DB::commit();
        return 1;

    }
    public static function setDistributionOrderFail($order_id): int
    {
        DB::beginTransaction();
        $record = DistributionOrder::whereOrderId($order_id)->lockForUpdate()->first();
        if (!$record){
            DB::rollBack();
            return 0;
        }
        if ($record->success > 0){
            DB::rollBack();
            return 0;
        }
        $record->success = 2;
        $record->save();
        DB::commit();
        return 1;

    }
}
